<template>
  <div>
    <heads />
    <Main :type="'form'">
      <el-form ref="form" label-width="150px" :model="form" :rules="form">
        <el-form-item
          label="自定义名称"
          prop="name"
          :rules="{
            required: true,
            message: '请输入自定义名称',
            trigger: 'blur'
          }"
        >
          <el-input
            v-model="form.name"
            class="form-input"
            size="medium"
            placeholder="请输入自定义名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="设置为默认配送方式"
          prop="is_default"
          :rules="{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }"
        >
          <el-switch
            v-model="form.is_default"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
          &nbsp;
          <span style="color:#909399">{{
            form.is_default ? "已开启" : "已关闭"
          }}</span>
        </el-form-item>
        <el-form-item
          label="配送范围"
          prop="distribution_scope"
          :rules="{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }"
        >
          <span class="form-info">收货地址在配送范围之外的买家将不可下单</span>
          <div>
            <el-radio-group v-model="form.distribution_scope">
              <el-radio :label="1">按服务半径</el-radio>
              <el-radio :label="2">按行政区域</el-radio>
              <el-radio :label="3">按门店分配</el-radio> </el-radio-group
            ><br />
          </div>
          <div v-if="form.distribution_scope == 1" class="interval">
            服务半径
            <el-input-number
              v-model.lazy="radius"
              size="small"
              class="form-min-input"
              :precision="0"
              :max="1000"
              :min="1"
              placeholder="请输入"
              :controls="false"
            ></el-input-number>
            公里
            <GDmap
              :type="'Circle'"
              style="margin-top:20px;"
              :datas="{ radius, lat, lng }"
              @retunrData="retunrData"
            />
          </div>
          <div v-else-if="form.distribution_scope == 2" class="interval">
            <el-form-item label="可配送区域" label-width="90px">
              {{ dataJson.area_name }} &nbsp;&nbsp;<el-button
                type="text"
                @click="editTemplate"
                >编辑</el-button
              ><br />
              <span class="form-info"
                >&nbsp;&nbsp;如启用第三方配送，请不要选择默认配送地址以外的城市区域</span
              >

              <linkage
                :dialog="dialog"
                :data-json="dataJson"
                :filter-arr="filterArr"
                @dialogShow="dialogShow"
              />
            </el-form-item>
          </div>
          <div v-else class="interval">
            <el-form-item label="可配送门店" label-width="90px">
              <el-button type="text" @click="xzStores">去选择</el-button><br />
              <Table :data="form.storesData" style="width:80%;">
                <el-table-column
                  label="门店名称"
                  align="center"
                  property="name"
                ></el-table-column>
                <el-table-column
                  label="门店地址"
                  align="center"
                  property="address"
                ></el-table-column>
                <el-table-column
                  label="门店标签"
                  align="center"
                  property="tag_name"
                ></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      @click="delStores(scope.$index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </Table>
              <div>
                可配送门店最远距离
                <el-input-number
                  v-model.lazy="form.maxDistance"
                  size="small"
                  class="form-min-input"
                  :precision="0"
                  :max="1000"
                  :min="0"
                  placeholder="请输入"
                  :controls="false"
                ></el-input-number>
                公里
              </div>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="配送价格">
          <el-form-item
            prop="distribution_start_fee"
            :rules="{
              required: true,
              message: '请输入配送价格',
              trigger: 'blur'
            }"
            label="起送价"
            class="interval"
            label-width="140px"
          >
            <el-input-number
              v-model="form.distribution_start_fee"
              size="small"
              class="form-min-input"
              :precision="2"
              placeholder="请输入配送价格"
              :controls="false"
            ></el-input-number
            >&nbsp;&nbsp;
            <span class="form-info"
              >订单中的商品在优惠前的金额（不包含运费）低于起送价时，买家将不能下单</span
            >
          </el-form-item>
          <el-form-item
            prop="distribution_base_fee"
            :rules="{
              required: true,
              message: '请输入基础运费',
              trigger: 'blur'
            }"
            label="基础运费"
            class="interval"
            label-width="140px"
          >
            <el-input-number
              v-model="form.distribution_base_fee"
              size="small"
              class="form-min-input"
              :precision="2"
              placeholder="请输入基础运费"
              :controls="false"
            ></el-input-number
            >&nbsp;&nbsp;
            <span class="form-info"
              >商家未设置阶梯价时，则所有订单统一运费标准；商家可按配送服务半径设置阶梯价</span
            >
          </el-form-item>
          <el-form-item label="启用阶梯价" class="interval" label-width="140px">
            <el-radio-group v-model="form.is_useup">
              <el-radio :label="1">开启</el-radio>
              <el-radio :label="0">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="form.is_useup">
            <el-form-item
              prop="start_radius"
              :rules="{
                required: true,
                message: '请输入起送半径',
                trigger: 'blur'
              }"
              label="起送半径"
              class="interval"
              label-width="140px"
            >
              <el-input-number
                v-model="form.start_radius"
                size="small"
                class="form-min-input"
                :precision="0"
                :controls="false"
              ></el-input-number
              >&nbsp;&nbsp;时,起送重量
              <el-input-number
                v-model="form.start_weight"
                size="small"
                class="form-min-input"
                :precision="0"
                :controls="false"
              ></el-input-number
              >&nbsp;&nbsp;时,使用基础运费
            </el-form-item>
            <el-form-item
              prop="increate_radius"
              :rules="{
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }"
              label="起送距离每增加"
              class="interval"
              label-width="140px"
            >
              <el-input-number
                v-model="form.increate_radius"
                size="small"
                class="form-min-input"
                :precision="0"
                :controls="false"
              ></el-input-number
              >&nbsp;&nbsp;时,运费增加
              <el-input-number
                v-model="form.increate_readius_fee"
                size="small"
                class="form-min-input"
                :precision="2"
                :controls="false"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              label="配送重量每增加"
              class="interval"
              label-width="140px"
            >
              <el-input-number
                v-model="form.increate_weight"
                size="small"
                class="form-min-input"
                :precision="0"
                :controls="false"
              ></el-input-number
              >&nbsp;&nbsp;时,运费增加
              <el-input-number
                v-model="form.increate_weight_fee"
                size="small"
                class="form-min-input"
                :precision="2"
                :controls="false"
              ></el-input-number>
            </el-form-item>
          </div>
          <div class="form-info">
            不超过起送半径和起送重量时，按基础运费计;起送重量为空时，按不限配送重量计算;<br />
            实际配送距离大于起送半径，不满增加公里数，运费按增加计算;实际配送重量大于起送重量，不满增加重量，运费按增加计算，依次类推;
          </div>
        </el-form-item>
        <el-form-item label="启动第三方配送">
          <el-switch
            v-model="form.is_third"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
          &nbsp;
          <span class="form-info"
            >{{ form.is_third ? "已开启" : "已关闭" }}&nbsp;&nbsp;&nbsp;&nbsp;
            开启后，将有第三方物流代您进行配送，配送产生的费用，将在余额中进行扣除。开启后表示已同意</span
          >
          <div v-if="form.is_third">
            <el-form-item label="第三方物流公司">
              <i class="el-icon-warning" style="font-size:14px;"></i>
              <el-button size="mini" type="text" @click="openLogistics">
                {{ form.third_logistics.length > 0 ? "去修改" : "去开启" }}
              </el-button>
              &nbsp;&nbsp;&nbsp;
              <span class="form-info">
                商户在发货时可选择将订单推送给第三方配送，第三方配送失败仍可自行配送</span
              >
            </el-form-item>
            <div>
              <el-button size="mini" type="text" @click="getSetting('sx')">
                刷新
              </el-button>
            </div>
            <div v-if="form.third_logistics.length > 0">
              <div
                v-for="(item, index) in form.third_logistics"
                :key="index"
                class="child-th"
              >
                <div class="imgs">
                  <img :src="$store.state.qiniu + item.img" />
                </div>
                <el-radio
                  v-model="item.is_default"
                  :label="1"
                  @change="radioTag(item.express_id, index)"
                  >设为默认</el-radio
                >
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="买家可选择配送时间"
          class="interval"
          prop="allow_distribution"
          :rules="{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }"
        >
          <el-switch
            v-model="form.allow_distribution"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
          &nbsp;
          <span class="form-info"
            >{{
              form.allow_distribution ? "已开启" : "已关闭"
            }}&nbsp;&nbsp;&nbsp;&nbsp;
            开启后，买家可在下单页选择配送时间，不开启则默认显示“立即配送”</span
          >

          <div v-if="form.allow_distribution">
            <el-form-item
              prop=""
              :rules="{
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }"
              label="起送时间"
              class="interval"
              label-width="140px"
            >
              <el-time-picker
                v-model="valTime"
                is-range
                size="small"
                value-format="HH:mm"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                style="margin-right:10px;"
              >
              </el-time-picker>
              <el-button size="small" @click="addTime">新增时间段</el-button>
            </el-form-item>
            <div class="timeC">
              <p
                v-for="(item, index) in timeArr"
                :key="index"
                class="time-chlid"
              >
                {{ item.start }}-{{ item.end }}
                <i class="el-icon-delete time-del" @click="timeDel(index)"></i>
              </p>
            </div>
            <el-form-item
              prop=""
              :rules="{
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }"
              label="买家至少提前"
              class="interval"
              label-width="140px"
            >
              <el-input-number
                v-model="form.pay_set1"
                size="small"
                style="width:50px;"
                :min="0"
                :precision="0"
                :controls="false"
              ></el-input-number
              >&nbsp;天&nbsp;
              <el-input-number
                v-model="form.pay_set2"
                size="small"
                style="width:50px;"
                :min="0"
                :max="23"
                :precision="0"
                :controls="false"
              ></el-input-number
              >&nbsp;小时&nbsp;
              <el-input-number
                v-model="form.pay_set3"
                size="small"
                style="width:50px;"
                :min="0"
                :max="59"
                :precision="0"
                :controls="false"
              ></el-input-number
              >&nbsp;分钟下单，且支持&nbsp;
              <el-input-number
                v-model="form.pay_set4"
                size="small"
                style="width:50px;"
                :min="1"
                :precision="0"
                :controls="false"
              ></el-input-number
              >&nbsp;天内配送
              <div class="form-info">
                买家仅可选择下单时间+设置时间之后的可配送时间段
              </div>
            </el-form-item>
            <el-form-item label="买家是否必填" label-width="140px">
              <el-radio-group v-model="form.is_require">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </el-form-item>
        <!-- <el-form-item label='自定义下单字段'>
            <el-button size='mini'
                       type='text'
                       @click='edit'> 编辑 </el-button>
            <el-button size='mini'
                       type='text'
                       @click='refresh'> 刷新 </el-button> <br />
            <div class='tables'>
              <el-table :data='form.tableData'
                        :header-row-style='{color:'#333333',fontSize: '14px',letterSpacing:'0.39px'}'
                        style='width:80%;'>
                <el-table-column label='字段名称'>
                  <template slot-scope='scope'>

                  </template>
                </el-table-column>
                <el-table-column label='字段格式'>
                  <template slot-scope='scope'>

                  </template>
                </el-table-column>
                <el-table-column label='是否必填'>
                  <template slot-scope='scope'>
                  </template>
                </el-table-column>
                <el-table-column label='排序'>
                  <template slot-scope='scope'>

                  </template>
                </el-table-column>

              </el-table>
              <div style='margin-top:10px;font-size:12px;'
                   class='add-form-item'>
                <el-button plain
                           @click='addTemplate'>新增自定义模板</el-button>
                &emsp;

              </div>

            </div>
          </el-form-item> -->
      </el-form>
    </Main>
    <Footer>
      <el-button type="primary" @click="submit">保 存</el-button>
    </Footer>
    <el-dialog
      title="选择门店"
      :visible.sync="dialogTableVisible"
      :before-close="handleClose"
    >
      <el-table
        ref="multipleTable"
        :data="form.storesList"
        :row-key="getRowKeys"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          width="30"
          :reserve-selection="true"
          type="selection"
        ></el-table-column>
        <el-table-column
          label="门店名称"
          align="center"
          property="name"
        ></el-table-column>
        <el-table-column
          label="门店地址"
          align="center"
          property="address"
        ></el-table-column>
        <el-table-column
          label="门店标签"
          align="center"
          property="tag_name"
        ></el-table-column>
      </el-table>
      <div style="width:100%;text-align:center;margin-top:30px;">
        <el-pagination
          :page-size="8"
          layout="prev, pager, next"
          :total="totals"
          @current-change="changes"
        >
        </el-pagination>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { SAMECITYSETTING } from "../../service";
import { STORE_LIST } from "@/service/shop";
import heads from "../component/heads";
export default {
  components: {
    linkage: r =>
      require.ensure([], () => r(require("publicCom/linkages")), "linkages"),
    GDmap: () => import("publicCom/GDmap"),
    heads
  },
  data() {
    return {
      radius: 1,
      longitude: "",
      latitude: "",
      lng: "",
      lat: "",
      form: {
        name: "",
        is_default: false,
        distribution_scope: 1,
        distribution_content: "",
        distribution_start_fee: "",
        distribution_base_fee: "",
        maxDistance: "",
        is_useup: 0,
        start_radius: "",
        start_weight: "",
        increate_radius: "",
        increate_readius_fee: "",
        increate_weight: "",
        increate_weight_fee: "",
        is_third: false,
        allow_distribution: false,
        aloow_distribution_time: "",
        pay_set1: 0,
        pay_set2: 0,
        pay_set3: 0,
        pay_set4: 1,
        is_require: 1,
        tableData: [
          {
            area: "所有区域默认配送",
            first: 1,
            first_price: 0,
            continuation: 1,
            continuation_price: 0
          }
        ],
        storesList: [],
        storesData: [],
        third_logistics: [],
        express_id: ""
      },
      valTime: "",
      timeArr: [],
      dialog: false,
      checked: true,
      templateName: "",
      dataJson: { area_name: "" },
      filterArr: [],
      dialogTableVisible: false,
      allList: [],
      getRowKeys(row) {
        return row.store_id;
      },
      totals: 0,
      pages: 1
    };
  },
  computed: {},
  created() {
    this.getSetting();
    this.getStoreList();
  },
  methods: {
    openLogistics() {
      let routeUrl = this.$router.resolve({
        name: "logistics",
        params: { id: 96 }
      });
      window.open(routeUrl.href, "_blank");
    },
    handleSelectionChange(v) {
      this.allList = v;
    },
    async getStoreList() {
      await STORE_LIST({
        page: this.pages,
        pageshow: 8
      }).then(res => {
        let { code, data, msg } = res;
        if (code === 200) {
          this.totals = data.count;
          this.form.storesList = data.data;
        } else {
          this.$message.error(msg);
        }
      });
    },
    changes(page) {
      this.pages = page;
      this.toggle();
      this.getStoreList();
    },
    handleSubmit() {
      this.form.storesData = this.allList;
      this.dialogTableVisible = false;
      this.allList = [];
    },
    handleClose() {
      this.dialogTableVisible = false;
      this.$refs.multipleTable.clearSelection();
      this.allList = [];
    },
    xzStores() {
      this.toggle();
      this.dialogTableVisible = true;
    },
    toggle() {
      this.form.storesList.forEach(ele => {
        this.form.storesData.forEach(eles => {
          if (ele.store_id === eles.store_id) {
            setTimeout(() => {
              this.$refs.multipleTable.toggleRowSelection(ele);
            }, 500);
          }
        });
      });
    },
    delStores(i) {
      this.form.storesData.splice(i, 1);
    },
    async getSetting(e) {
      await SAMECITYSETTING().then(res => {
        let { code, data } = res;
        if (code === 200) {
          this.form.name = data.name;
          this.form.is_default = data.is_default === 1;
          this.form.distribution_scope = data.distribution_scope;
          if (data.distribution_scope === 1) {
            data.distribution_content = data.distribution_content.split(",");
            this.longitude = data.distribution_content[1];
            this.latitude = data.distribution_content[2];
            this.lng = data.distribution_content[1];
            this.lat = data.distribution_content[2];
            this.radius = data.distribution_content[0];
          } else if (data.distribution_scope === 2) {
            this.dataJson = data.distribution_content[0];
          } else {
            this.form.storesData = data.stores;
            this.form.maxDistance = data.max_distance;
          }
          this.form.distribution_start_fee = data.distribution_start_fee;
          this.form.distribution_base_fee = data.distribution_base_fee;
          this.form.is_useup = data.is_useup;
          this.form.start_radius = data.start_radius;
          this.form.start_weight = data.start_weight;
          this.form.increate_radius = data.increate_radius;
          this.form.increate_readius_fee = data.increate_readius_fee;
          this.form.increate_weight = data.increate_weight;
          this.form.increate_weight_fee = data.increate_weight_fee;
          if (!e) {
            this.form.is_third = data.is_third === 1;
          }
          this.form.third_logistics = data.third_logistics;
          this.form.allow_distribution = data.allow_distribution === 1;
          if (data.allow_distribution) {
            this.timeArr = [];
            let arr = data.aloow_distribution_time.split(",");
            arr.forEach(ele => {
              ele = ele.split("-");
              this.timeArr.push({ start: ele[0], end: ele[1] });
            });
          }
          data.pay_set = data.pay_set.split(",");
          this.form.pay_set1 = data.pay_set[0];
          this.form.pay_set2 = data.pay_set[1];
          this.form.pay_set3 = data.pay_set[2];
          this.form.pay_set4 = data.pay_set[3];
          this.form.is_require = data.is_require;
        }
      });
    },
    addTime() {
      if (this.valTime) {
        if (this.timeArr.length > 0) {
          let v = this.valTime[0].replace(/:/g, "");
          let t = this.timeArr[this.timeArr.length - 1].end.replace(/:/g, "");
          if (parseInt(v) < parseInt(t)) {
            this.$message.error("新添加时间段不能早于已添加时间段内");
            return;
          }
        }
        this.timeArr.push({ start: this.valTime[0], end: this.valTime[1] });
      } else {
        this.$message.error("请选择时间段");
      }
      this.valTime = "";
    },
    timeDel(i) {
      this.timeArr.splice(i, 1);
    },
    edit() {
      window.open("/order/orderList");
    },
    editTemplate() {
      this.dialog = true;
    },
    dialogShow(e) {
      this.dialog = false;
      if (e) {
        this.dataJson.areaJson = e.areaJson;
        this.dataJson.area_name = e.area_name;
        this.dataJson.plan_id = e.plan_id;
      }
    },
    // addTemplate () {
    //   let tableid = '1' + new Date().getTime().toString().substring(8) + Math.floor(Math.random() * (99 - 10)) + 1

    //   this.form.tableData.push({ tableid, area: '', first: 1, first_price: 0, continuation: 1, continuation_price: 0 })
    // },
    // delTemplate (i) {
    //   this.form.tableData.splice(i, 1)
    // },
    retunrData(e) {
      if (e) {
        this.longitude = e.lng;
        this.latitude = e.lat;
      }
    },
    async submit() {
      let distributionContent;
      let paySet;
      let aloowDistributionTime = [];
      if (this.form.distribution_scope === 1) {
        distributionContent = `${this.radius},${this.longitude},${this.latitude}`;
      } else if (this.form.distribution_scope === 2) {
        distributionContent = this.dataJson.plan_id;
      } else {
        let arr = [];
        this.form.storesData.forEach(ele => {
          arr.push(ele.store_id);
        });
        distributionContent = arr.join(",");
      }
      this.timeArr.forEach(ele => {
        aloowDistributionTime.push(ele.start + "-" + ele.end);
      });
      paySet = `${this.form.pay_set1},${this.form.pay_set2},${this.form.pay_set3},${this.form.pay_set4}`;
      let param = {
        flag: "save",
        name: this.form.name,
        is_default: this.form.is_default ? 1 : 0,
        distribution_scope: this.form.distribution_scope,
        max_distance: this.form.maxDistance,
        distribution_content: distributionContent,
        distribution_start_fee: this.form.distribution_start_fee,
        distribution_base_fee: this.form.distribution_base_fee,
        is_useup: this.form.is_useup,
        start_radius: this.form.start_radius,
        start_weight: this.form.start_weight,
        increate_radius: this.form.increate_radius,
        increate_readius_fee: this.form.increate_readius_fee,
        increate_weight: this.form.increate_weight,
        increate_weight_fee: this.form.increate_weight_fee,
        is_third: this.form.is_third ? 1 : 0,
        allow_distribution: this.form.allow_distribution ? 1 : 0,
        aloow_distribution_time: aloowDistributionTime.join(","),
        pay_set: paySet,
        is_require: this.form.is_require,
        express_id: this.form.express_id
      };

      await this.$refs["form"].validate(valid => {
        if (valid) {
          SAMECITYSETTING(param).then(res => {
            let { code, msg } = res;
            if (code === 200) {
              this.$emit("out");
            }
            this.$message({
              message: msg,
              type: code === 200 ? "success" : "error"
            });
          });
        }
      });
    },
    radioTag(expressId, i) {
      this.form.express_id = expressId;
      this.form.third_logistics.forEach(ele => {
        ele.is_default = 0;
      });
      this.form.third_logistics[i].is_default = 1;
    }
  }
};
</script>
<style lang="scss" scoped>
.switchs {
  margin: 20px 16px;
  font-size: 20px;
  font-weight: bold;
  padding-left: 20px;
}

.tabs {
  width: 58px;
  margin-left: 60px;
}
.news {
  height: 80px;
  text-align: left;
  line-height: 70px;
  padding-left: 20px;
  border-bottom: 10px solid #f3f3f3;
  span {
    font-size: 14px;
    color: #aaaaaa;
  }
}
.interval {
  margin-bottom: 20px;
}
.timesInterval {
  width: 50%;
  height: 100px;
  background: #f2f2f6;
  border-radius: 6px;
  padding: 10px 50px;
  font-size: 12px;
}
.timeC {
  width: 80%;
  display: flex;
  .time-chlid {
    width: 130px;
    height: 40px;
    text-align: center;
    color: #fff;
    background: #c0c4cc;
    position: relative;
    margin: 0 10px 10px 0;
    &:hover .time-del {
      display: inline-block;
    }
    .time-del {
      position: absolute;
      top: 3px;
      right: 3px;
      color: #f56c6c;
      cursor: pointer;
      display: none;
    }
  }
}
.child-th {
  float: left;
  width: 140px;
  height: 94px;
  .imgs {
    width: 120px;
    height: 70px;
    border-radius: 6px;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
